﻿using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;

namespace ED.RabbitMQ
{
    /// <summary>
    /// RabbitMQ扩展配置类
    /// </summary>
    public static class RabbitMQExtensions
    {
        public static IServiceCollection AddRabbitMQ(this IServiceCollection services, Action<RabbitMQConfig> setupOptions)
        {
            RabbitMQConfig rabbitMQConfig = new RabbitMQConfig();
            setupOptions.Invoke(rabbitMQConfig);
            services.AddSingleton<IConnectionFactory>(_ => new ConnectionFactory()
            {
                HostName = rabbitMQConfig.HostName,
                Port = rabbitMQConfig.Port,
                UserName = rabbitMQConfig.UserName,
                Password = rabbitMQConfig.Password
            });
            services.AddSingleton(_ => _.GetRequiredService<IConnectionFactory>().CreateConnection());
            return services;
        }
    }
}